package com.yztc.youbadbad.ui.other.activity;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.Gravity;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.tiffany.greendao.DaoSession;
import com.tiffany.greendao.ProductDao;
import com.yztc.youbadbad.App;
import com.yztc.youbadbad.R;
import com.yztc.youbadbad.bean.homepage.ProductBean;
import com.yztc.youbadbad.bean.other.ProductInfoBean;
import com.yztc.youbadbad.constant.MyConstants;
import com.yztc.youbadbad.helper.BitmapCircleTransformation;
import com.yztc.youbadbad.presenter.ProductInfoPresenterImpl;
import com.yztc.youbadbad.ui.other.activity.interfaces.CommodityInfoInterfaces;
import com.yztc.youbadbad.utils.ToastUtils;
import com.yztc.youbadbad.utils.UIManager;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.SaveListener;


/**
 * 商品详情的Activity
 */
public class CommodityInfoActivity extends AppCompatActivity
        implements CommodityInfoInterfaces.IProductInfoView {

    @BindView(R.id.product_add_shoppingcar)
    TextView productAddShoppingcar;
    @BindView(R.id.progressBar)
    ProgressBar progressBar;
    @BindView(R.id.product_image)
    ImageView productImage;
    @BindView(R.id.brand_name)
    TextView brandName;
    @BindView(R.id.name)
    TextView name;
    @BindView(R.id.store_price)
    TextView storePrice;
    @BindView(R.id.home_market_price)
    TextView homeMarketPrice;
    @BindView(R.id.activity_icon)
    ImageView activityIcon;
    @BindView(R.id.country_flag)
    ImageView countryFlag;
    @BindView(R.id.country_name)
    TextView countryName;
    @BindView(R.id.cart_shoppingcar)
    ImageView cartShoppingcar;


    private Context mContext = this;
    private PopupWindow mPopupWindow;
    private ImageView iconPop;
    private TextView pricePop;
    private TextView substactPop;
    private TextView numberPop;
    private TextView addPop;
    private Button confirmPop;

    private String product_id;//id
    private String storePrice1;//价格
    private String product_image;//图片
    private ProductBean product;
    private DaoSession daoSession = App.newInstance().getDaoSession();
    private ProductDao productDao;
    private String name1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_commodity_info);
        ButterKnife.bind(this);

        initData();

    }


    //初始化页面并 网络访问
    private void initData() {
        if (getIntent() != null) {
            product = (ProductBean) getIntent().getParcelableExtra(MyConstants.KEY_PRODUCET_DETAIL);
            product_id = product.getProduct_id();

            brandName.setText(product.getBrand_name());
            countryName.setText(product.getCountry_name());
            name1 = product.getName();
            this.name.setText(name1);
            storePrice1 = "￥ " + product.getStore_price();//商品价格
            storePrice.setText(storePrice1);
            product_image = product.getProduct_image();
            Glide.with(mContext).load(product_image).into(productImage);
            Glide.with(mContext).load(product.getCountry_flag())
                    .transform(new BitmapCircleTransformation(mContext))
                    .into(countryFlag);

            //发起网络请求
            CommodityInfoInterfaces.IProductInfoPresenter infoPresenter = new ProductInfoPresenterImpl(this);
            infoPresenter.getProdectInfoInternetData(product_id);
        }

    }


    /**
     * 点击事件监听
     *
     * @param view
     */
    @OnClick({R.id.product_back, R.id.product_share, R.id.product_add_shoppingcar,
            R.id.product_immediately_parchase,R.id.cart_shoppingcar})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.product_back://返回
                finish();
                break;
            case R.id.product_share://分享
                break;
            case R.id.product_add_shoppingcar://加入购物车
                showPopupWindow();//显示popupwindow
                backgroundAlpha(this, 0.5f);//0.0-1.0
                break;
            case R.id.product_immediately_parchase://马上购买
                break;
            case R.id.cart_shoppingcar:
                UIManager.startMain(mContext, 4);
                finish();

        }
    }


    /**
     * 显示加入购物车的popupWindow
     */
    private void showPopupWindow() {
        //设置contentView
        final View contentView = getLayoutInflater().inflate(R.layout.popupwindow_bottom, null);
        int density = (int) getResources().getDisplayMetrics().density;
        mPopupWindow = new PopupWindow(contentView,
                ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT, true);
        mPopupWindow.setContentView(contentView);
        mPopupWindow.setOutsideTouchable(true);  //设置点击屏幕其它地方弹出框消失
        contentView.setOnTouchListener(new View.OnTouchListener() {

            public boolean onTouch(View v, MotionEvent event) {

                int height = contentView.findViewById(R.id.pop_layout).getTop();
                int y = (int) event.getY();
                if (event.getAction() == MotionEvent.ACTION_UP) {
                    if (y < height) {
                        mPopupWindow.dismiss();
                    }
                }
                return true;
            }
        });
        initPopupWindowView(contentView);

        View rootview = getLayoutInflater().inflate(R.layout.activity_commodity_info, null);
        mPopupWindow.showAtLocation(rootview, Gravity.BOTTOM, 0, 0);

        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                backgroundAlpha(CommodityInfoActivity.this, 1f);
            }
        });
    }

    //初始化popupwindow内容
    private void initPopupWindowView(View contentView) {
        //设置各个控件的点击响应
        iconPop = (ImageView) contentView.findViewById(R.id.icon_pop);
        pricePop = (TextView) contentView.findViewById(R.id.price_pop);
        substactPop = (TextView) contentView.findViewById(R.id.substact_pop);
        numberPop = (TextView) contentView.findViewById(R.id.number_pop);
        addPop = (TextView) contentView.findViewById(R.id.add_pop);
        confirmPop = (Button) contentView.findViewById(R.id.confirm_pop);


        pricePop.setText(storePrice1);//价格
        Glide.with(mContext).load(product_image).into(iconPop);//图标
        substactPop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(numberPop.getText().toString());
                if (num == 1) {
                    ToastUtils.showToast(CommodityInfoActivity.this, "最小购买量为1");
                } else {
                    numberPop.setText(--num + "");
                }
            }
        });
        addPop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(numberPop.getText().toString());
                numberPop.setText(++num + "");
            }
        });
        confirmPop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int num = Integer.parseInt(numberPop.getText().toString());
                product.setNum(num);

                product.save(new SaveListener<String>() {
                    @Override
                    public void done(String objectId,BmobException e) {
                        if(e==null){
                            //ToastUtils.showToast(CommodityInfoActivity.this, "添加数据成功，返回objectId为："+objectId);
                            ToastUtils.showToast(CommodityInfoActivity.this, "添加成功");
                        }else{
                            //ToastUtils.showToast(CommodityInfoActivity.this,"创建数据失败：" + e.getMessage());
                            ToastUtils.showToast(CommodityInfoActivity.this, "添加失败");
                        }
                    }
                });
               /* productDao = daoSession.getProductDao();
                Product product = new Product(product_id, name1, product_image, storePrice1, num);
                Product unique = productDao.queryBuilder()//检查是否存过
                        .where(ProductDao.Properties.Product_id.eq(product_id))
                        .unique();
                if (unique == null) {//未添加
                    //String product_id, String name, String product_image, String store_price, Integer num
                    productDao.insert(product);
                } else {
                    product.setNum(product.getNum() + unique.getNum());
                    productDao.update(product);
                }*/

                mPopupWindow.dismiss();//結束popupwindow

            }

        });

    }

    /**
     * 设置添加屏幕的背景透明度
     *
     * @param bgAlpha
     */
    public void backgroundAlpha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }


    @Override
    public void getProdectInfoInternetData(ProductInfoBean productInfoBean) {
        ProductInfoBean.DataBean.BrandInfoBean brandInfo = productInfoBean.getData().getBrandInfo();

    }

    @Override
    public void showProgressBar() {
        progressBar.setVisibility(View.VISIBLE);
    }

    @Override
    public void hideProgressBar() {
        progressBar.setVisibility(View.GONE);
    }

    @Override
    public void showErrorMessage() {
        ToastUtils.showEorrorToast(mContext);
        progressBar.setVisibility(View.GONE);
    }
}
